import { Component, OnInit } from '@angular/core';
import { JsonApiService } from "app/core/api/json-api.service"; //http请求配置引入
import { Router, ActivatedRoute } from "@angular/router"; //路由引入
import { config } from '../../../shared/smartadmin.config';
declare var $: any;
@Component({
	selector: 'sa-threshold',
	templateUrl: './threshold.component.html',
})
export class ThresholdComponent implements OnInit {
	tableData = []; //table数据
	totalCount: number = 0; //分页总条数
	curPage: number = 1; //分页当前页
	pageSize: number = 10; //内置的分页每页条数
	searchKey: string = ''; //搜索keyword
	startTime_table: string = '';
	endTime_table: string = '';
	selectedCompanyId: string = '';
	selectedCompanyName: string = '';
	carNumber: string = '';
	deviceId: string = '';
	jumpData: any; // 跳转页面接收到的数据
	initDateRange: any = {
		startTime: '',
		endTime: '',
	}// 时间组件需要渲染的值
	validatorOptions = {
		excluded: [":disabled"],
		feedbackIcons: {
			valid: 'glyphicon glyphicon-ok',
			invalid: 'glyphicon glyphicon-remove',
			validating: 'glyphicon glyphicon-refresh'
		},
		fields: {
			carNumberFrom: {
				trigger:"change",
				validators: {
					notEmpty: {
						message: '请选择车牌号'
					}
				}
			},
			overSpeed: {
				validators: {
					notEmpty: {
						message: '请输入超速阈值'
					}
				}
			},
			speedingTime: {
				validators: {
					notEmpty: {
						message: '请输入超速时长'
					}
				}
			},
			overLoad: {
				validators: {
					notEmpty: {
						message: '请输入超载阈值'
					}
				}
			},
			overLoadTime: {
				validators: {
					notEmpty: {
						message: '请输入超载时长'
					}
				}
			}
		}
	}
	constructor(private jsonApiService: JsonApiService, private router: Router, private activatedRoute: ActivatedRoute) {
		activatedRoute.queryParams.subscribe(queryParams => {
			this.curPage = queryParams.nowPage || 1;
			if (common.getCookie('jumpTo/langyun/calibration')) {
				this.jumpData = JSON.parse(common.getCookie('jumpTo/langyun/calibration'));
				this.initDateRange.startTime = this.jumpData.startTime;
				this.initDateRange.endTime = this.jumpData.endTime;
			}
		});
	}

	ngOnInit() {
		let that = this;
		if (common.getCookie('jumpTo/langyun/calibration')) {
			setTimeout(() => {
				that.load();
			}, 100)
			common.clearCookie('jumpTo/langyun/calibration');
		} else {
			this.load();
		}
	}

	// 接收子组件传递过来的数据 
	getSelectTableTime(time) {
		this.startTime_table = time.startTime;
		this.endTime_table = time.endTime;
	}
	// 公司选中回调
	companySelected(data) {
		this.selectedCompanyId = data.companyId;
		this.selectedCompanyName = data.companyName;
		this.deviceId = data.deviceId;
		this.carNumber = data.carNumber;
	}
	//表格搜索
	table_search() {
		this.curPage = 1
		this.searchKey = common.stringTrim(this.searchKey);
		this.load();
	}
	//刷新
	refresh() {
		this.load();
	}
	//初始化加载list数据
	load() {
		let data = {
			pageSize: this.pageSize,
			nowPage: this.curPage,
			parameters: {
				companyId: this.selectedCompanyId,
				deviceId: this.deviceId,
				//				carNumber: this.carNumber,
				startTime: this.startTime_table,
				endTime: this.endTime_table,
				searchKey: this.searchKey,
			}
		}
		let reqdata = 'gridPager=' + JSON.stringify(data);
		this.jsonApiService.http("thresholdSetting/thresholdSettingList.html", reqdata).subscribe(data => {
			this.tableData = data.exhibitDatas;
			this.totalCount = data.recordCount;
		})
	}
	//分页回调
	paginate(e) {
		this.curPage = e.page + 1;
		this.pageSize = e.rows;
		this.load();
	}
	//导出报表
	exportData() {
		let parameters = {
			companyId: this.selectedCompanyId,
			//deviceId: this.deviceId,
			carNumber: this.carNumber,
			startTime: this.startTime_table,
			endTime: this.endTime_table,
			type: '1',
			//searchKey: this.searchKey,
		};
		let timeCheck=common.correctTime(parameters);
		if(!timeCheck.status){
			this.jsonApiService.message(timeCheck.message);
			return;
		}
		let paramsName = 'param';
		let _url = config.BaseURL + 'calibrationData/export.html';
		common.exprotDataFile(parameters, paramsName, _url);
	}
	// 页面跳转
	jumpCarList(row) {
		let BaseURL = window.location.protocol + '//' + window.location.hostname + ':' + window.location.port;
		common.setCookie('jumpTo/system/car', JSON.stringify(row));
		window.open(BaseURL + '#/system/car');
	}

	/**
	 *  数据新增模块 
	 */
	formType: string = 'new';
	thresholdFrom: any = {
		id: null,
		carNumber: '',
		deviceId: '',
		overSpeed: '',
		speedingTime: '',
		overLoad: '',
		overLoadTime: '',
		commandTime:''
	}
	// 车辆组件数据回调
	optionSelected(data) {
		this.thresholdFrom.carNumber = data.text;
		this.thresholdFrom.deviceId = data.id;
		$("#carNumberFrom").val(data.text?data.text:'')
		$("#carNumberFrom").trigger("change")
	}
	addRow(modal) {
		this.formType = 'new'
		this.thresholdFrom = {
			id: '',
			carNumber: '',
			deviceId: '',
			overSpeed: '',
			speedingTime: '',
			overLoad: '',
			overLoadTime: '',
			commandTime:'',
		}
		var str=$("<span class='select2-selection__placeholder'>请选择</span>");
		$('#carNumberFrom').val("");
		$('#carSelect2').val("");
		$("#select2-carSelect2-container").empty();
		$("#select2-carSelect2-container").attr("title","");
		$("#select2-carSelect2-container").prepend(str);
		modal.show();
	}

	// 编辑
	editRow(row, modal) {
		modal.show();
		this.formType = 'update'
		this.thresholdFrom = JSON.parse(JSON.stringify(row))
		$("#select2-carSelect2-container").html('<span class="select2-selection__clear">×</span>' + row.carNumber)
	}

	issueInstructions(row) {
		this.jsonApiService.confirm_message("确定给该车辆下发指令么?").then(() => {
			let reqdata = 'id=' + row.id;
			this.jsonApiService.http("thresholdSetting/issueInstructions.html", reqdata).subscribe(data => {
				this.jsonApiService.message(data.message);
				if (data.code == 0) {
					this.load();
				}
			})
		})
	}
	// 取消提交
	modalClose(modal) {
		$("#thresholdValFrom").data('bootstrapValidator').resetForm();
		modal.hide();
	}
	// 数据提交
	modalSubmit(modal) {
		$('#thresholdValFrom').bootstrapValidator('validate'); //开启验证
		let isValid = $('#thresholdValFrom').data('bootstrapValidator').isValid();  //验证是否通过
		if (isValid) {

			if (this.formType == "new") {
				this.jsonApiService.http_obj("thresholdSetting/add.html", this.thresholdFrom).subscribe(data => {
					this.jsonApiService.message(data.message);
					this.modalClose(modal);
					this.load();
				})
			} else {
				// 删除为null的字段
				for(let key in this.thresholdFrom){
					if(!this.thresholdFrom[key]&&this.thresholdFrom[key]!=0){
						delete this.thresholdFrom[key]
					}
				}
				this.jsonApiService.http_obj("thresholdSetting/edit.html", this.thresholdFrom).subscribe(data => {
					this.jsonApiService.message(data.message);
					this.modalClose(modal);
					this.load();
				})
			}
		}

	}
	
	clearObj:any={
		carNumber:'',
		deviceId:''
	}
	// 清零
	clearRow(modal){
		this.clearObj={
			carNumber:'',
			deviceId:''
		}
		var str=$("<span class='select2-selection__placeholder'>请选择</span>");
		$('#carNumberFrom').val("");
		$('#clearCarSelect2').val("");
		$("#select2-clearCarSelect2-container").empty();
		$("#select2-clearCarSelect2-container").attr("title","");
		$("#select2-clearCarSelect2-container").prepend(str);
		modal.show()
	}
	clearCarSelected(data){
		this.clearObj.carNumber = data.text;
		this.clearObj.deviceId = data.id;
		// $("#clearCarNumberFrom").val(data.text?data.text:'')
		// $("#clearCarNumberFrom").trigger("change")
	}
	clearmodalClose(modal){
		modal.hide();
	}
	clearmodalSubmit(modal){
		if(!this.clearObj.carNumber){
			this.jsonApiService.message("请选择要清零的车牌号");
			return;
		}
		// 增加确认清零操作
		this.jsonApiService.confirm_message("确定给车辆 ["+this.clearObj.carNumber+"] 进行清零?").then(() => {
			this.jsonApiService.http_obj("thresholdSetting/cleared.html", this.clearObj).subscribe(data => {
				this.jsonApiService.message(data.message);
				this.clearmodalClose(modal);
				this.load();
			})
		})
	}

	numInputChange(value){
		console.log(value)
	}
}